﻿namespace Digitalmes.Core.Common.Extensions;

/// <summary>
/// 枚举扩展。
/// </summary>
public static class EnumExtensions
{
    /// <summary>
    /// 获取枚举的 <see cref="DescriptionAttribute"/> 属性值，若没则返回枚举本身名称。
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="enumValue">枚举值</param>
    /// <returns></returns>
    public static string Description<TEnum>(this TEnum enumValue) where TEnum : Enum
    {
        var fieldName = enumValue.ToString();
        MemberExpression memberExpression = Expression.Field(null, typeof(TEnum), fieldName);
        var attribute = memberExpression.Member.GetCustomAttribute<DescriptionAttribute>(false);
        return attribute != null ? attribute.Description : fieldName;
    }

    /// <summary>
    /// 合并带有 <see cref="FlagsAttribute"/> 标识的枚举实例。
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="enumValue">枚举实例</param>
    /// <returns></returns>
    public static IReadOnlyList<TEnum> SplitEnum<TEnum>(this TEnum enumValue) where TEnum : Enum
    {
        var result = new List<TEnum>();
        foreach (TEnum item in Enum.GetValues(typeof(TEnum)))
        {
            int value = Convert.ToInt32(item);
            int source = Convert.ToInt32(enumValue);
            if ((value & source) == value)
            {
                result.Add(item);
            }
        }
        return result;
    }
}
